<?php
namespace app\common\model;

class Users extends Base
{
    public static function search($id)
    {
        $page = input('post.page/d');
        $pageSize = input('post.pageSize/d');
        $page = ($page < 1) ? 1 : $page;
        $pageSize = ($pageSize < 1 || $pageSize > 50) ? 10 : $pageSize;
        $self = new static();
        $query = $self->alias('a');
        $query->where('a.web_id', '=', $id);
        $uid = input('post.uid');
        !empty($uid) && $query->where('a.uid', '=', $uid);
        $type = input('post.type');
        if (!empty($type) && $type == 0) {
            $query->where('a.vipstart', 'eq', '');
        } elseif (!empty($type) && $type == 1) {
            $query->where('a.vipstart', 'neq', '');
        } elseif (!empty($type) && $type == 2) {
            $query->where('a.dlpower', 'neq', 0);
        }
        $query2 = clone $query;
        return [
            'total' => $query2->count('a.uid'),
            'list' => $query->page($page, $pageSize)->order('a.regtime desc')->select()
        ];
    }

    public static function login($userInfo)
    {
        $self = new static();
		$str = $userInfo['username'] . $userInfo['password'] . time() . real_ip();
		$sign = md5($str . md5('11144452888'));
		$userInfo = $self->where('username', '=' ,$userInfo['username'])->find();
		cookie("pskey",authcode($userInfo['uid'], 'ENCODE', md5($str)));
        cookie("skey",md5($str));
		cookie("sid",$sign);
        $update = $self->where('uid', '=', $userInfo['uid'])
            ->update([
				'skey' => md5($str),
                'sid' => $sign,
                'dlip' => real_ip(),
                'city' => get_ip_city(real_ip()),
                'time' => time()
            ]);
        if ($update) {
            return true;
        } else {
            return false;
        }
    }
	
	public static function reg($data)
    {
        $self = new static();
		$insert['web_id'] = WEB_ID;
        $insert['username'] = $data['username'];
		$insert['nickname'] = $data['nickname'];
		$insert['password'] = make_Hash($data['password']);
        $insert['qq'] = $data['qq'];
		$insert['mail'] = $data['mail'];
		$insert['skey'] = '0';
        $insert['regtime'] = date("Y-m-d H:i:s");
        $insert['regip'] = real_ip();
        $insert['time'] = time();
		 if (config('sys_reg_free_vip') == 1) {
            $insert['vipstart'] = date('Y-m-d H:i:s');
            $insert['viptime'] = date('Y-m-d', strtotime('+ ' . config('sys_reg_free_vip_day') . ' day'));
        }
        if (config('sys_reg_free_peie') == 1) {
            $insert['peie'] = config('sys_reg_free_peie_num') == '' ? 0 : config('sys_reg_free_peie_num');
        }
        if (config('sys_reg_free_rmb') == 1) {
            $insert['money'] = config('sys_reg_free_money_num');
        }
        $check = $self->insert($insert);
        if ($check) {
            return true;
        } else {
            return false;
        }
    }
	
	public
    static function dlyz($qq)
    {
        $self = new static();
        $user = $self->where('qq', '=', $qq)->find();
        if ($user && $user['dlpower'] == 1) {
            $result = [
                'code' => 0,
                'message' => '<table class="table"><tbody><tr><td><font color="green">' . $qq . '代理身份认证成功,可以放心交易</font></td></tr><tr><td>代理等级：银牌代理</td></tr><tr><td>查询时间：' . date('Y-m-d H:i:s') . '</td></tr></tbody></table>'
            ];
        } elseif ($user && $user['dlpower'] == 2) {
            $result = [
                'code' => 0,
                'message' => '<table class="table"><tbody><tr><td><font color="green">' . $qq . '代理身份认证成功,可以放心交易</font></td></tr><tr><td>代理等级：金牌代理</td></tr><tr><td>查询时间：' . date('Y-m-d H:i:s') . '</td></tr></tbody></table>'
            ];
        } elseif ($user && $user['dlpower'] == 3) {
            $result = [
                'code' => 0,
                'message' => '<table class="table"><tbody><tr><td><font color="green">' . $qq . '代理身份认证成功,可以放心交易</font></td></tr><tr><td>代理等级：钻石代理</td></tr><tr><td>查询时间：' . date('Y-m-d H:i:s') . '</td></tr></tbody></table>'
            ];
        } else {
            $result = [
                'code' => 1,
                'message' => '该QQ认证代理失败，请谨慎交易！'
            ];
        }
        return $result;
    }
	
	public
    static function checkUsername($username)
    {
		$self = new static();
		if(!$row=$self->where("username",$username)->find()){
			return true;
		}else{
			return false;
		}
    }
	
	public
    static function checkQq($qq)
    {
		$self = new static();
		if(!$row=$self->where("qq",$qq)->find()){
			return true;
		}else{
			return false;
		}
    }
	
	public
    static function checkPass($userInfo)
    {
		$self = new static();
		$user_row = $self->where('username', '=', $userInfo['username'])->field('password')->find();
        if (password_verify($userInfo['password'], $user_row['password'])) {
			return true;
		}else{
			return false;
		}
    }

    public static function profile($data)
    {
        $self = new static();
        switch (true) {
				case (!$data['mail']):
                $result['code'] = 1;
                $result['message'] = '请输入邮箱账号';
                break;
            case ($self->where('mail', '=', $data['mail'])->find()):
                $result['code'] = 1;
                $result['message'] = '该邮箱已被注册！';
                break;
            default:
                $self->where('uid', '=', $data['uid'])->update([
                    'mail' => $data['mail']
                ]);
                $result['code'] = 0;
                $result['message'] = '资料完善成功！';
                //修改验证码状态
                Captcha::where('code', '=', $data['code'])->update([
                    'status' => 1
                ]);
        }
        return $result;
    }

    public
    static function change_Password($uid, $data)
    {
        $self = new static();
        $validate = validate('Users');
        if (!$validate->scene('changePass')->check($data)) {
            $result = [
                'message' => $validate->getError(),
                'code' => 1
            ];
        } else {
            $user_row = $self->where('uid', '=', $uid)->field('password')->find();
            if (password_verify($data['outpass'], $user_row['password'])) {
                $new_pass = make_Hash($data['password']);
                if ($self->where('uid', '=', $uid)->update(['password' => $new_pass])) {
                    Users::logout();
                    $result = [
                        'code' => 0,
                        'message' => '修改密码成功，请重新登录',
						'url' => url('index/index/login')
					];
                }
            } else {
                $result = [
                    'code' => 1,
                    'message' => '原密码不正确！'
                ];
            }
        }
        return $result;
    }
	
	public
    static function change_Nickname($uid, $data)
    {
        $self = new static();
		if ($self->where('uid', '=', $uid)->update(['nickname' => $data['name']])) {
			$result = [
				'code' => 0,
				'message' => '修改昵称成功'
			];
		}
        return $result;
    }
	
	public
    static function change_Qq($uid, $data)
    {
        $self = new static();
		$user_row = $self->where('uid', '=', $uid)->field('password')->find();
		if(Users::checkQq($data['qq']) != true){
        	$result = [
				'code' => 1,
				'message' => 'QQ已被其他用户绑定'
			];
        }elseif (password_verify($data['password'], $user_row['password'])) {
			if ($self->where('uid', '=', $uid)->update(['qq' => $data['qq']])) {
				$result = [
					'code' => 0,
					'message' => '修改绑定QQ成功'
				];
			}
		} else {
			$result = [
				'code' => 1,
				'message' => '密码不正确！'
			];
		}
        return $result;
    }
	
    public
    static function YpayVip($userInfo, $data)
    {
        if (config('sys_is_shop_vip_zk') == 1) {
            //计算折扣后的价格
            $price = config('sys_' . $data['shop'] . '_price_' . $data['shopid']);
            $zk = config('sys_shop_' . $data['shop'] . '_zk_' . $data['shopid'] . '');
            $res_price = round($price * $zk / 10, 2);
        } else {
            $res_price = config('sys_' . $data['shop'] . '_price_' . $data['shopid']);
        }
        if ($res_price <= $userInfo['money']) {
            //开通时间
            $vip_start = date("Y-m-d");
            //计算开通的vip时长
            if ($userInfo['viptime']) {
                $vip_time = date("Y-m-d", strtotime("+" . is_vip_day($data['shopid']) . " day", strtotime($userInfo['viptime'])));
            } else {
                $vip_time = date("Y-m-d", strtotime("+" . is_vip_day($data['shopid']) . " day"));
            }
            $new_money = $userInfo['money'] - $res_price;
            //修改用户信息
            $up_user = Users::where('uid', '=', $userInfo['uid'])
                ->field('vipstart,viptime,money')
                ->update([
                    'vipstart' => $vip_start,
                    'viptime' => $vip_time,
                    'money' => $new_money
                ]);
            if ($up_user) {
                $result = [
                    'code' => 0,
                    'message' => '开通会员成功，感谢您的购买！'
                ];
            } else {
                $result = [
                    'code' => -1,
                    'message' => '购买失败，服务器繁忙！'
                ];
            }
        } else {
            $result = [
                'code' => 1,
                'message' => '您的账户余额不足，请充值或选择其它支付方式'
            ];
        }
        return $result;
    }

    public
    static function YpayPeie($userInfo, $data)
    {
        //判断站点是否开启商品促销
        if (config('sys_is_shop_pe_zk') == 1) {
            //计算折扣后的价格
            $price = config('sys_' . $data['shop'] . '_price_' . $data['shopid']);
            $zk = config('sys_shop_' . $data['shop'] . '_zk_' . $data['shopid'] . '');
            $res_money = round($price * $zk / 10, 2);
        } else {
            $res_money = config('sys_' . $data['shop'] . '_price_' . $data['shopid']);
        }
        if ($res_money <= $userInfo['money']) {
            //获取购买配额数量
            $res_peie = is_peie_num($data['shopid']);
            //计算用户配额总数
            $all_peie = $userInfo['peie'] + $res_peie;
            //计算用户剩下的余额
            $new_money = $userInfo['money'] - $res_money;
            //修改用户信息
            $up_user = Users::where('uid', '=', $userInfo['uid'])
                ->field('peie,money')
                ->update([
                    'peie' => $all_peie,
                    'money' => $new_money
                ]);
            if ($up_user) {
                $result = [
                    'code' => 0,
                    'message' => '购买额度成功，感谢您的购买！'
                ];
            } else {
                $result = [
                    'code' => -1,
                    '购买失败，服务器繁忙！'
                ];
            }
        } else {
            $result = [
                'code' => 1,
                'message' => '您的账户余额不足，是否立即充值？'
            ];
        }
        return $result;
    }

    public
    static function updateByUid($uid, $data)
    {
        $self = new static();
        if ($result = $self->where('uid', '=', $uid)->update($data)) {
            return $result;
        } else {
            return false;
        }
    }
	
	public
    static function updateByUsername($username, $data)
    {
        $self = new static();
        if ($result = $self->where('username', '=', $username)->update($data)) {
            return $result;
        } else {
            return false;
        }
    }

    public
    static function delByUid($uid)
    {
        $self = new static();
        if ($result = $self->where('uid', '=', $uid)->delete()) {
            return $result;
        } else {
            return false;
        }
    }

    public
    static function getLoginUser()
    {
        $self = new static();
		$skey = cookie("skey");
        $pskey = authcode(cookie('pskey'), 'DECODE', $skey);
        //获取登录Cookie
        $uid = $pskey;
        //组成查询条件
        $where['uid'] = $uid;
        //通过Cookie存储的数据查询数据库记录
        if (!$uid || !$userInfo = $self->where($where)->find()) {
            //不存在
            return false;
        } else {
            //存在则返回该用户的这条记录内容
            return $userInfo;
        }
    }

    public
    static function checkLogin()
    {
		$skey = cookie("skey");
		if(!$skey){
			$result = [
				'url' => url('index/login'),
				'msg' => '请登录后再进行操作！'
			];
		}else{
			$self = new static();
			$sid = cookie("sid");
			$pskey = authcode(cookie('pskey'), 'DECODE', $skey);
			$user = $self
					->where('uid', '=',$pskey )
					->find();
			if ($sid == $user['sid']) {
				if ($user['skey'] === $skey) {
					$result = null;
				} else {
					$result = [
						'url' => url('index/login'),
						'msg' => '请登录后再进行操作！'
					];
				}
			} else {
				cookie('skey', null);
				cookie('sid', null);
				cookie('pskey', null);
				$result = [
					'url' => url('index/login'),
					'msg' => '您的账号在别处登录，请重新登录！'
				];
			}
		}
        return $result;
    }

    public
    static function logout()
    {
		cookie('skey', null);
		cookie('sid', null);
		cookie('pskey', null);
        cookie('user_token', null);
        return true;
    }
}